package com.example.dragcontentviewdemo.helper.internal.animationlistener;

import android.animation.ValueAnimator;
import android.graphics.drawable.Drawable;
import android.view.View;

import com.example.dragcontentviewdemo.helper.internal.connector.AttachInfo;
import com.example.dragcontentviewdemo.helper.internal.util.CaculatorUtil;

/**
 * 视图移动回原始位置时的过程动画监听器, 尽管这个类被分到一个独立的文件
 * 但是它的动作却不是解耦的，它所做的事情与绑定的view直接相关
 */
public class MoveBackAnimationUpdateListener implements ValueAnimator.AnimatorUpdateListener {
    private static final int CONSTANT_MAX_COLOR_BIT_VALUE = 255; //RGB最大值
    private AttachInfo mAttachInfo;
    private View mView;
    private float mCurrAlpha;

    /*
    需要确保mDecorView 不为空此处，在实例化此类时.
     */
    public MoveBackAnimationUpdateListener(View viewOfAnimation, AttachInfo info){
        mView = viewOfAnimation;
        mAttachInfo = info;
    }

    public void updateCurrAlpha(){
        mCurrAlpha = mAttachInfo.mDecorView.getBackground().getAlpha();
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {

        if(mAttachInfo.callback!=null) {
            final float fraction = CaculatorUtil.calculateTranslationXFraction(mView);
            mAttachInfo.callback.onMoved(fraction,mAttachInfo.mDirection);
        }
        //fraction == 1 时应该调整至不透明
        int alpha = (int) (mCurrAlpha + (CONSTANT_MAX_COLOR_BIT_VALUE - mCurrAlpha) * animation.getAnimatedFraction());
        Drawable background = mAttachInfo.mDecorView.getBackground();
        background.setAlpha(alpha);
        mAttachInfo.mDecorView.invalidateDrawable(background);
    }

}